<template>
    <el-dialog v-model="dialogFormVisible" title="文件上传">
        <el-upload ref="upload" class="upload" :multiple="true" :action="action" :auto-upload="false" :headers="header"
            :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <template #trigger>
                <el-button type="primary">选择文件</el-button>
            </template>
            <el-button style="margin-left: 10px;" type="success" @click="submitUpload">
                上传至服务器
            </el-button>
            <template #tip>
                <div class="el-upload__tip text-red">
                    文件大小不能超过50mb
                </div>
            </template>
        </el-upload>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="fileUpload">
import { ref, onMounted } from "vue";
import { ElMessage } from 'element-plus'
import { Decrypt } from '@/utils/secret.js'

const dialogFormVisible = ref(false)
const header = ref()
const action = ref(import.meta.env.VITE_BASE_URL + '/system/file/upload?business=系统文件上传')
const upload = ref()
const beforeAvatarUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 50;
    if (!isLt2M) {
        ElMessage.error('上传文件大小不能超过50MB!');
    }
    return isLt2M;
}
const handleAvatarSuccess = (res) => {
    if (res.code === 200) {
        ElMessage.success('上传文件成功')
    } else {
        ElMessage.error(res.msg)
    }
}
const submitUpload = () => {
    upload.value.submit()
}
onMounted(() => {
    let str = window.localStorage.getItem("access-admin")
    let user = JSON.parse(str)
    const token = Decrypt(user.token)
    header.value = { token: token, accessAuthor: 'allow' }
})

defineExpose({
    dialogFormVisible
});
</script>
<style scoped lang="less"></style>